package cn.sciento.starter.keyencrypt.mvc;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.keyencrypt.core.EncryptContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.PriorityOrdered;

public class EncryptHeaderContextFilter implements Filter, PriorityOrdered {
  private static final Logger logger = LoggerFactory.getLogger(EncryptHeaderContextFilter.class);
  
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}
  
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
      HttpServletRequest servletRequest = (HttpServletRequest)request;
      String encrypt = servletRequest.getHeader("H-Request-Encrypt");
      if (EncryptContext.isAllowedEncrypt() && StringUtils.isNotEmpty(encrypt)) {
        EncryptContext.setEncryptType(encrypt);
      }
      chain.doFilter(request, response);
    } finally {
      EncryptContext.clear();
    } 
  }
  
  @Override
  public void destroy() {}
  
  @Override
  public int getOrder() {
    return 2147483597;
  }
}
